<template>
  <div>
    <div id="container" ref="box"></div>
  </div>
</template>

<script>
  import * as THREE from "three";
  import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls.js';
  import {Stats} from 'three/examples/js/libs/stats.min.js';
  export default {
        name: "My3D001",
        data(){
          return{
            camera:null,
            scene:null,
            renderer:null,
            mesh:null,
            mesh2:null,
            mesh3:null,
            controls:null,
            selectObject:null,
            stats:null
          }
        },
    mounted() {
          this.init();
          this.animate();
          this.$refs.box.addEventListener('click',this.onMouseDblclick, false);
    },
    methods:{
      init(){
        //创建场景对象Scene
        this.scene = new THREE.Scene();
        //创建网格模型 并设置其参数和材质
        let geometry = new THREE.BoxGeometry(0.2,0.2,0.2);
        geometry.name="two";
        let material = new THREE.MeshNormalMaterial({
          color:0x0000ff,
          opacity:0.7, //透明度设置，0表示完全透明，1表示完全不透明
          transparent:true //是否开启透明，默认false
        });
        this.mesh = new THREE.Mesh(geometry,material);
        //将创建的网格添加到场景中
        this.scene.add(this.mesh);

        let geometry2 = new THREE.BoxGeometry(0.2,0.2,0.2);
        geometry2.name = "threeG";
        var material2=new THREE.MeshPhongMaterial({
            color:0xff0000,
            specular:0x4488ee, //高光颜色
            shininess:12, //反光度
            opacity:0.4,
            transparent:true
        });
        this.mesh2 = new THREE.Mesh(geometry2,material2);
        this.mesh2.position.x =0.4;
        this.scene.add(this.mesh2)

        let geometry3 = new THREE.BoxGeometry(0.2,0.2,0.2);
        geometry3.name="oneG";
        var material3=new THREE.MeshPhongMaterial({
            color:0xff0000,
            specular:0x4488ee, //高光颜色
            shininess:12, //反光度
            opacity:0.4,
            transparent:true
        });
        this.mesh3 = new THREE.Mesh(geometry3,material3);
        this.mesh3.position.x =-0.4;
        this.scene.add(this.mesh3)
        //创建点光源
        var point = new THREE.PointLight(0xffffff);
        point.position.set(400,200,300);
        this.scene.add(point);
        //创建环境光
        var anbient = new THREE.AmbientLight(0x444444);
        this.scene.add(anbient);

        //相机设置
        let container = document.getElementById("container");
        this.camera = new THREE.PerspectiveCamera(
          70,
          container.clientWidth /container.clientHeight,
          0.01,//三维场景显示范围控制系数，系数越大，显示的范围越大
           10);
        this.camera.position.z = 1;
        /**
         * 创建渲染器
         */
        this.renderer = new THREE.WebGL1Renderer({antialias:true});
        this.renderer.setSize(container.clientWidth,container.clientHeight);//设置渲染区域尺寸
        this.renderer.setClearColor(0xb9d3ff,1);//设置背景颜色
        container.appendChild(this.renderer.domElement);//将渲染器绑定到div标签

        //创建控件对象
        this.controls = new OrbitControls(this.camera,this.renderer.domElement);
        //坐标轴
        // var axisHelper = new THREE.AxesHelper(250);
        // this.scene.add(axisHelper);

      },
      //动画
      animate(){
        requestAnimationFrame(this.animate);//定时调用animate函数，实现物体的旋转
        this.mesh.rotation.x += 0.01;
        this.mesh.rotation.y += 0.02;
        this.mesh2.rotateX(Math.PI/160);
        this.mesh2.rotateY(Math.PI/180);
        this.mesh3.rotateX(Math.PI/160);
        this.mesh3.rotateY(Math.PI/180);
        // this.mesh2.rotationX += 0.01;
        // this.mesh2.rotationY += 0.02;
        // if (this.selectObject != undefined && this.selectObject != null){
        //     this.renderDiv(this.selectObject);
        // }
        this.renderer.render(this.scene,this.camera);
      },
      //鼠标双击触发的方法
       onMouseDblclick(event) {
          //获取raycaster和所有模型相交的数组，其中的元素按照距离排序，越近的越靠前
          let intersects = this.getIntersects(event);
          console.log(intersects)

          //获取选中最近的Mesh对象
          if (intersects.length !== 0) {
            console.log("测试选中了几何体:"+intersects[0].object.geometry.name)
              this.selectObject = intersects[0].object;
              this.changeMaterial(this.selectObject);
          } else {
              alert('选了个寂寞！！');
          }
        },
      getIntersects(event){
        event.preventDefault();// 阻止默认的点击事件执行, https://developer.mozilla.org/zh-CN/docs/Web/API/Event/preventDefault
        console.log("event.clientX:" + event.clientX);
        console.log("event.clientX:" + event.clientY);

        //声明 rayCaster 和 mouse 变量
        let rayCaster = new THREE.Raycaster();
        let mouse = new THREE.Vector2();

        //通过鼠标点击位置，计算出raycaster所需点的位置，以屏幕为中心点，范围-1到1
        mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
        mouse.y = -(event.clientY / window.innerHeight) * 2 + 1; //这里为什么是-号，没有就无法点中

        //通过鼠标点击的位置(二维坐标)和当前相机的矩阵计算出射线位置
        rayCaster.setFromCamera(mouse, this.camera);

        //获取与射线相交的对象数组， 其中的元素按照距离排序，越近的越靠前。
        let intersects = rayCaster.intersectObjects(this.scene.children);

        //返回选中的对象
        return intersects;
    },
    changeMaterial(object) {

      var material =new THREE.MeshLambertMaterial({

      color:0xffffff * Math.random(),

      transparent: object.material.transparent ?false :true,

      opacity:0.8

            });

            object.material = material;
  },
    renderDiv(object){
        //获取窗口的一半高度和宽度
        let halfWidth = window.innerWidth / 2;
        let halfHeight = window.innerHeight / 2;

        //逆转相机求出二维坐标
        let vector = object.position.clone().project(camera);

        //修改div的位置
        $("#container").css({
            left: vector.x * halfWidth + halfWidth,
            top: -vector.y * halfHeight + halfHeight - object.position.y
        });
        //显示模型信息
        $("#container").text("name:" + object.name);
    },
   
   
       
    }

  }
  

</script>

<style scoped>
#container{
  position: absolute;
  width: 100%;
  height: 100%;
}
</style>
